package com.push.notnoop.biyao.com;

import java.util.ArrayList;
import java.util.List;
import java.util.Queue;

import com.notnoop.apns.APNS;
import com.notnoop.apns.ApnsService;

public class IOSPushMutiRunnable implements Runnable{
//	private String keystore  = Global.getConfig().getProperty("ios_push_certification");
//	private String password  = Global.getConfig().getProperty("ios_push_password");
	private static String keystore = IOSPushRunnable.class.getClassLoader().getResource("").getPath()+"biyaoPush.p12";
	private static String password = "biyaoPush";
	private ApnsService apnsService = APNS.newService().withCert(keystore, password).withProductionDestination().build();
	
	private static final int DEVICE_NUM_PER_PUDH = 10;  // 一次请求发送10个token
	
	private String payload;
	private Queue<String> queue;
	
	public IOSPushMutiRunnable(String payload,Queue<String> queue){
		this.payload = payload;
		this.queue   = queue;
	}
	
	public void run() {
		List<String> deviceBuf = new ArrayList<String>();
		
		while ( true ) {
        	String token = queue.poll();
        	if(token != null  ){
        		deviceBuf.add(token);
        	}
        	
        	// 缓存满或者最后一次时，集中发送
        	if( deviceBuf.size() >= DEVICE_NUM_PER_PUDH ||  ( deviceBuf.size() > 0 && token == null)   ){
        		apnsService.push(deviceBuf, payload);
        		deviceBuf.clear();
        		
        		// 等待数据传出，防止数据在网络中积压
        		try {
					Thread.sleep(50);
				} catch (Exception e) {
					e.printStackTrace();
				}
        	}
        	
        	// 如果队列为空，暂停后重试
        	if( token == null ){
        		try {
					Thread.sleep(2000);
				} catch (Exception e) {
					e.printStackTrace();
				}
        	}
        } 
	}


}
